Click Here!



home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Bug Proofing Visual Basic: A Guide to Error Handling and Prevention
(Publisher: John Wiley & Sons, Inc.)
Author(s): Rod Stephens
ISBN: 0471323519
Publication Date: 11/01/98

Search this book:
 
Previous Table of Contents Next


INTRODUCTION

Every program more than 10 lines long contains at least one bug.

While the preceding statement may not be provable, it is generally a good assumption. Removing absolutely every bug from any nontrivial program is an extremely difficult task. Proving every bug has been removed is even harder. To prove a program contains a bug, you need only demonstrate the bug. To prove that a program has no bugs is much more difficult.

In fact, some software development models assume that all complex programs have bugs and that they can never be completely removed. The goal is not to remove all of the bugs from the application, but to remove so many that those remaining appear only very rarely to the end users.

Visual Basic provides an environment for writing applications while minimizing bugs that is unmatched by other languages. Visual Basic’s runtime libraries handle many of the messier details of Windows programming, removing a huge source of potential bugs. By automatically freeing objects that are not referenced, Visual Basic eliminates a wide assortment of memory handling errors that are quite troublesome in other languages.

Unless you have programmed extensively in Delphi, C++, or some other more powerful and flexible language, you cannot fully appreciate how many bugs Visual Basic prevents before they arise. It only takes a few hours tracking an obscure pointer problem in C++ to make you appreciate the fact that Visual Basic does not have pointers. More powerful and flexible languages let you do many things that are difficult in Visual Basic, but one of those things is to write bugs that are really hard to fix.

For other kinds of errors, Visual Basic’s family of On Error statements allows a program to anticipate errors and take action to recover from them. The Err object allows a program to simulate errors for testing, or to generate new errors of its own.Finally, Visual Basic’s integrated development environment includes excellent debugging features. It allows you to step through your program, set breakpoints on specific lines of code, examine and modify values, set watches to monitor values as they change, change the program’s point of execution, and even interactively modify the source code without interfering with the running program.While Visual Basic provides all these potent tools, it is up to you to take advantage of them. The programming environment alone cannot guard against every possible kind of bug. If your program sets a variable to the value 17 when it should have the value 7, Visual Basic cannot know this is an error. You must detect this bug and use the development environment to find and fix the problem.

Many Visual Basic books mention bugs in passing. Most describe Visual Basic’s On Error statements, but they cover On Error only briefly. The On Error statement itself cannot prevent, identify, or remove bugs, however. It merely allows the program to keep running in spite of them.

Bug Proofing Visual Basic explains bug prevention, detection, and eradication in Visual Basic. It tells how to design and implement code that prevents bugs from occurring in the first place. It explains techniques you can use to make your code expose bugs instead of hiding them. It shows how to test code so you can catch and fix bugs as quickly as possible. Finally, it explains how to bugproof Visual Basic programs so they can continue to run even if a bug slips through the design and testing process and is shipped to a user.

What This Book Provides

Bug Proofing Visual Basic has three goals: to explain how to code to prevent bugs from occurring, to show how to handle unexpected bugs that do occur, and to explain how to locate and fix those bugs. This book explains how to

•  Code proactively to prevent bugs before they start
•  Use coding and naming conventions to prevent bugs
•  Write code that exposes bugs instead of hiding them
•  Catch bugs quickly before they do serious harm
•  Find bugs using tools like the debugger and code profiler
•  Use debug and runtime versions of a program to make debugging easier
•  Use On Error statements to handle unexpected conditions
•  Record information automatically so you can fix bugs after users encounter them

Intended Audience

Before reading Bug Proofing Visual Basic, you should have some familiarity with Visual Basic, but you do need not be an expert. The book does not require any advanced knowledge of Visual Basic. If you have read any introduction to Visual Basic programming, you will have no trouble reading this book.

It can even be argued that it is more important for beginners to read Bug Proofing Visual Basic than for advanced programmers. After years of experience, many advanced programmers have learned some of the topics presented here the hard way, through trial and error. By reading this book, a beginner can learn these tricks and techniques quickly and easily without suffering the same pain and aggravation. The beginner can also develop sound programming practices before acquiring bad habits that will be hard to break.

Visual Basic Version Compatibility

The best programming techniques depend on fundamental programming concepts, not the idiosyncrasies of a particular version of a programming language. In fact, many apply in any programming language, not just Visual Basic. Much of what you learn from this book applies equally to Visual Basic versions 3, 4, 5, 6, or even Delphi and C++.

Most of the examples presented here are written in Visual Basic 4 and they run in Visual Basic 4, 5, and 6. The majority of the principles apply to any version of the language, although the details may be slightly different. The three main exceptions to this are Debug.Assert, classes, and the Visual Basic Code Profiler VBCP.

The Debug.Assert statement was not introduced to the language until Visual Basic 5 so you cannot use it if you are running an earlier version of Visual Basic. The Debug.Assert statement is quite useful for detecting bugs. This book explains how to use the statement and how to achieve similar effects in earlier versions of Visual Basic.

Classes were introduced to the language in Visual Basic 4. If you have Visual Basic 3 or some older version, you cannot create classes so you can ignore the parts of this book that deal with classes and objects.

Finally, the Visual Basic Code Profiler VBCP is provided with the Professional and Enterprise editions of Visual Basic. If you own one of the more restrictive editions, you cannot use the profiler so you can skip the chapter that discusses it.Programs that do not work in Visual Basic 4 include the following:

Chapter 5, program Circles5. This program uses default values and optional parameters that are not variants. These features work only in Visual Basic 5 and 6.
Chapter 11, programs Bad11 and Good11. This chapter discusses optimizations that apply to compiled native code executables. Since Visual Basic 4 does allow you to create a native code executable, these programs only make sense in Visual Basic 5 and 6.
Chapter 13, programs Showerr. This program uses the vbMsgBoxHelpButton constant to make a message box present a help button. That constant was introduced by Visual Basic 5, so this program only runs in Visual Basic 5 and 6. However, if you remove this button, you can make the program run in Visual Basic 4 as well.

Programming languages often grow, but they rarely shrink. It is unlikely that Microsoft will remove the On Error GoTo statement or Debug.Assert in future versions of Visual Basic. That means the techniques explained in this book should be useful for many years to come. If any changes are necessary, they will be posted at this book’s Web site at www.vb-helper.com/err.htm.

Chapter Overviews

Bug Proofing Visual Basic is divided into five parts that cover major topics in bug prevention, detection, and removal. The parts generally follow the sequence of events in an application’s development cycle. They progress from code creation topics to error handling, testing, and debugging.

While the parts are arranged in roughly chronological order, there is a lot of overlap between topics in a typical project. For example, when a developer finds a bug during testing, he switches into debugging mode to find the bug. He then switches into development mode to fix the bug using good coding techniques that, hopefully, will not cause another bug. He then switches back into test mode to test the bug fix, and finally returns to the original task of testing the application as a whole.

The chapters in this book are relatively independent so you can read them in any order, even jumping from part to part if you wish. In fact, you may find it more interesting to skip around a little. If you grow tired of the development chapters, jump ahead to the testing chapters for a while.

A few topics are repeated in similar forms in different chapters. These topics affect development in multiple ways. For instance, Chapter 6, “Being Obvious,” and Chapter 9, “Design,” both mention declaring parameters with the ByVal keyword because you should think about ByVal during design and coding.

The parts of the book and their chapters are:

Part One. Work Environment

This may seem like a strange place to begin. After all, a good developer can program at any time and in any place. However, environmental factors can have a huge impact on the number of bugs you introduce. A distracting or tense environment may make you program quickly and sloppily to meet scheduled deadlines. That adds bugs to the code.

The chapters in this part of the book discuss environmental issues you should consider in your quest to produce high-quality code.

1.  Programming Philosophy. In bug prevention, attitude is everything. This chapter describes the proper mindset for preventing and removing bugs quickly and easily.
2.  Work Habits. This chapter discusses more specific techniques that can make bug management easier. Little things, like keeping a list of bugs you have encountered, can make identifying and fixing similar bugs easier in the future.

Part Two. Coding Style

This part of the book discusses specific Visual Basic coding style conventions you can use to make code easier to read and maintain. These chapters read like a list of commandments: do this, do that, do not do the other. In most of these suggestions, consistency is more important than the exact details. If you do not like a rule, change it. It does not really matter how you capitalize global variable names, as long as everyone on your project does it the same way.

3.  Variables. This chapter describes methods for declaring and using variables to minimize the chances of introducing bugs.
4.  Constants and Enums. Constants and enumerated values are important resources for reducing bug counts. This chapter explains how to use them to make code more readable and maintainable.
5.  Exposing Bugs. Many programming practices considered safe actually hide bugs. This chapter shows how to write code that exposes bugs instead of hiding them.
6.  Being Obvious. Program code should not be mysterious to programmers who read it. This chapter explains ways you can write code that is obvious to others.
7.  Comments. Comments help bridge the gap between a program written for a computer to execute and humans trying to understand the code. This chapter shows how to use comments to help readers understand the code so they do not add bugs to it later.
8.  Gotchas. This chapter describes some bugs that are common in Visual Basic programs and tells how to avoid them. Some are rather subtle and can waste a lot of your time if you have never seen them before. They have certainly wasted a lot of my time.

Part Three. Development

Part Three deals mostly with development issues at a higher level than Part Two does. These include application and subroutine design issues, and optimization.

9.  Design. Design decisions can have a large impact on the bugginess and maintainability of an application. This chapter gives some tips on designing maintainable applications.
10.  Encapsulation. Encapsulation is both an old and new idea. Many object-oriented programmers treat encapsulation as a new concept invented by object-oriented languages. Actually, many programming constructs provide some degree of encapsulation. This chapter explains how to use variables, classes, subroutines, and other programming devices to encapsulate complex functionality and make it more bugproof.
11.  Optimization. Optimization and bugproofing are often contradictory goals. Optimizing code often makes it harder to understand. On the other hand, bugproofing requires that the code be as easy to understand as possible. This chapter explains how and when to optimize while keeping the program reasonably bugproof.

Part Four. Error Handling

Even if you do your work properly, use good coding style, and follow practices to prevent bugs, errors will still occur. Inevitably, some bugs will slip through despite your best efforts. Other unexpected situations, like the user opening the floppy drive door or deleting a critical file, can still happen.

The chapters in Part Four explain how to handle these unexpected situations. They show how to build error handlers that allow a program to continue execution even when the unforeseen occurs.

12.  Error Handling Fundamentals. This chapter describes Visual Basic’s error handling mechanism: the family of On Error statements. A program can use On Error statements to prepare for almost any eventuality.
13.  Standard Error Handlers. Many programs perform the same sorts of actions when they encounter errors. For example, they might log error information to a file to help developers find the bug later. This chapter describes several standard error handlers you can use to log errors for later analysis.

Part Five. Post-Coding Activities

Many developers believe their job is to simply write a bunch of code. After they write a piece of code, they rush on to something else. Occasionally, a bug might materialize and require attention, but in the meantime, the developer concentrates on something else.

Writing the code is not the final step. The developer must still test, debug, profile, and optimize the code. Then an independent tester must test the code to see if the developer missed anything, and the components of the system must be tested together. Finally, after the product is certified and released to end users, the development team should carry out a project postmortem to see if they can learn from their mistakes.

The chapters in this part of the book discuss activities developers should perform after writing code.

14.  Testing. Many programmers consider testing to be a necessary evil that occurs at the end of a project. In fact, testing must occur during all stages of the project. This chapter describes testing habits and techniques you can use to prevent unwanted surprises from ambushing the project in its final stages.
15.  Profiling. The code profiler that comes with the Professional and Enterprise editions of Visual Basic allows you to generate coverage and performance statistics for an application. Using these statistics, you can identify code that needs optimization or that may contain bugs. This chapter describes the profiler and explains how to use it to look for bugs.
16.  Debugging Habits. Just as good habits can make coding and testing easier and more effective, good debugging habits can help you find and fix bugs more effectively. This chapter describes debugging habits that will help you make your debugging sessions more productive.

Appendices

Appendix A. This appendix contains an explanation of the self-test code presented in each chapter. It describes the bad points demonstrated by example programs and provides an improved implementation.
Appendix B. This appendix contains blank header comments you can use as templates in your programs. These templates are described in Chapter 7, “Comments,” and are available electronically on the book’s Web site at www.vb-helper.com/err.htm.

Writing Style

As you read this book, you will notice that it takes a rather authoritarian approach. It may seem as if it is saying, “Do this, do that, and don’t do the other.” Do not interpret these statements as dictatorial pronouncements from some programming hack with an inflated sense of his own importance. I do not pretend to know everything there is to know about programming.

The suggestions in this book are meant as advice only, not as unwavering rules. It was just much easier to write the suggestions as rules rather than filling the text with the phrases “you might consider...” and “a technique that is often useful is . . .”

Over the years I have spent hundreds of hours chasing bugs caused by myself and others. My goal with this book is to let you painlessly learn some of the lessons I learned through trial and error. If this book saves you more than the time it takes you to read it, I consider it a success.

If one of the suggestions does not fit in with your development environment, modify or ignore it. In many cases, it is more important that your programming team be consistent than that you follow the rules presented here exactly. For example, it does not really matter whether you declare global variables with LeadingCapitals, firstWordLowercase, or With_Underscores, as long as you all follow the same practice. Consistency is the key. Modify the specifics of the rules to suit your project’s style.

A Note on Creativity

These suggestions may also seem like an attempt to stifle your creativity as a programmer. Some programmers become emotionally attached to their coding style and resent attempts to coerce them into following standard style guidelines.

The intent of this book is not to strangle creativity. Programming is an extremely creative process. It takes great skill and imagination to decide how to implement a certain behavior in a program. Joining together the pieces of code built by a team of different developers can be challenging and rewarding. Removing creativity from application development would make it impossible.

On the other hand, many programmers use their creativity in unproductive ways. They spend extra effort naming variables after pets or characters in Monty Python movies so they can get a chuckle when the variables come together in a certain line of code. Creativity belongs in the design, not in the implementation. Turning a detailed design into source code should be a straightforward, mechanical process. The code should be uncomplicated enough for another programmer to easily read and understand it. Interesting surprises and plot twists belong in fiction, not in program source code. This is one place where dull is beautiful. Make your application seen by the user be the work of art, not the source code seen by the programmer.

Common Sense

Rules that are common sense are easy to follow. Common sense tells you not to pass a police officer at 75 mph when the speed limit is 25 mph. This is a reasonably obvious rule that it is easy to remember and follow.

Unfortunately, computers have little to do with common sense. Until you understand all their strange little quirks and peccadilloes, the things they do can seem odd. You need to understand the strange ways in which the computer sometimes interprets seemingly ordinary commands.

Many of the suggestions in this book are common sense when you think about them properly. If you adjust your mindset, you can turn almost all of them into common sense. As you work through the book, you will learn new ways to think about programming. These new ways of thinking will mean the difference between just following a bunch of rules by rote and generalizing the rules to cover new situations.

After you learn to place ease of maintenance over conciseness, readability over execution speed, and bug identification over bug avoidance, the rest of the guidelines will seem obvious. Hopefully, by the time you have finished, you will be able to sum this book up in three words: Use common sense.

How to Use This Book

The chapters in this book are reasonably independent so you can read them in any order. You can even jump from one part of the book to another. In fact, you may find it more interesting to skip around a little. If you grow tired of the chapters on coding style, jump ahead to the testing chapter for a while.

Each chapter includes a “Self-Test” section that lets you make use of the concepts described in the chapter. Many of these sections include source code that disobeys the suggestions made in the chapter. You can examine the code and identify changes you could make to improve the code and make it more bugproof.

Each chapter also contains a “Bug Stopper” section that lists the key points covered by that chapter.

Appendix A, “Self-Test Solutions,” contains improved solutions and answers. Note that there are as many possible solutions as there are programming styles. Appendix A shows one possible improved solution, but not necessarily the only one. Your solution may be different from the one in Appendix A but it may be equally correct. As suggested implementations are modified and when other examples are developed, they will be posted at the book’s Web site at www.vb-helper.com/err.htm.

Updates and Feedback

Updates to this book will be posted at the book’s Web site at www.vb-helper.com/err.htm. These will include new techniques for managing error handling in future versions of Visual Basic. They will also include useful techniques submitted by readers.

If you have questions, comments, or suggestions, or if you want to share your bug prevention, detection, and eradication techniques with others, send email to the author at RodStephens@vb-helper.com.

What’s Next?

Time to get started! Turn the page or, if you feel daring, jump to the middle of the book and start reading. Examine the suggestions and work through the self-tests.

Then make the techniques described here your own. Take notes. Scribble in the margins. Cross things out and write in modifications to suit your project’s style. Use sticky notes to mark things you want to discuss with other project members.Finally, and most importantly, apply them. You will not get the full benefit of this book until its guidelines become habits. Then you will be able to spend less time finding and fixing bugs and more time doing what you really wanted to do when you became a programmer: programming.


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.